package com.epoch.client.kernel.serve;

import com.epoch.client.kernel.constant.CommonStorage;
import com.epoch.common.Message;
import com.epoch.common.MessageType;
import com.epoch.common.User;
import com.epoch.common.UserRegister;
import com.epoch.common.loader.ParameterLoader;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;

/**
 * @author Seon
 * @date 2022/10/21 21:28
 */
@Slf4j
public class ClientConnService {
    /**
     * 用户注册
     * @param register 注册用户
     * @return 注册结果
     */
    public boolean checkUserSignup(UserRegister register){
        boolean result = false;
        try {
            Socket socket = getSocket();
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            //将用户注册信息发送给服务器
            oos.writeObject(register);
            //实例化对象输入流，接收服务器回送的用户注册信息
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Message message = (Message)ois.readObject();
            if (message.getMessageType().equals(MessageType.MESSAGE_REGISTER_SUCCESS)){
                log.info(message.getSenderName() + "注册成功！");
                result = true;
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean userAuthentication(Object o) {
        //布尔类型的变量用于表明用户是否合法
        boolean result = false;
        try {
            Socket socket = getSocket();
            ObjectOutputStream oos  = new ObjectOutputStream(socket.getOutputStream());
            User user = (User) o;
            //设置信息类型
            user.getMessage().setMessageType(MessageType.MESSAGE_LOGIN_SUCCESS);
            //设置时间
            user.getMessage().setDate(new Date());

            oos.writeObject(user);
            log.info("对象包已发送"+user);
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            log.info("返回信息：");
            //读取服务器回送的对象信息
            Message message = (Message)ois.readObject();
            //验证用户的登录
            if (message.getMessageType().equals(MessageType.MESSAGE_LOGIN_SUCCESS)) {
                log.info(user.getName() + "登录成功！");
                //把Socket放入管理之中
                CommonStorage.REPOSITORY.put("user", message.getDynamicData().get("user"));
                SocketMappingManager.addSocket(user.getName(), socket);
                result = true;
            } else {
                log.error("登录失败");
                return false;
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

    private Socket getSocket() throws IOException {
        return new Socket(ParameterLoader.HOST, ParameterLoader.PORT);
    }
}
